package com.dingpeikeji.quickdeer.mobile.service;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.modules.cupons.entity.CuponsInfo;
import com.dingpeikeji.quickdeer.core.modules.cupons.service.TCuponsService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersService;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.base.web.FSysController;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.DemandsReact;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProRentOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TDemands;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FDemandsService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.dingpeikeji.quickdeer.utils.StringUtil;
import com.google.common.collect.Lists;

@Service
@Transactional(readOnly = true)
public class MobileDemandService {
	@Autowired
	private FDemandsService demandsService;
	@Autowired
	private TOrdersService tOrdersService;
	@Autowired
	private FrontUserService userService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private TCargotypeService tCargotypeService;
	@Autowired
	private FrontUserService frontUserService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private TCuponsService tCuponsService;
	@Autowired
	private OrderService orderService;
	//获取车型数据
	public BackResult getCargotypeList() {
		List<TCargotype> cargotypeList = tCargotypeService.getCargotypeListForMobile();
		if (cargotypeList.size()==0||cargotypeList==null) {
			return BackResult.build("200", "未查询到数据");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cargotypeList", cargotypeList);
		return BackResult.ok(map);
	}
	//定制包车填写
	public BackResult saveDemand(TDemands tDemands,HttpServletRequest request) {
		String siteid = tSitedtlService.getSiteIdByName(request.getParameter("departcity.sitename"));
		TSitedtl tSitedtl = tSitedtlService.get(siteid);
		tDemands.setDepartcity(tSitedtl);
		if (siteid==null||"".equals(siteid)||"null".equals(siteid)||"null\n".equals(siteid)) {
			return BackResult.build("400", "暂不支持此地区定制包车业务");
		}
		String fromdateStr = request.getParameter("fromdata");
		tDemands.setFromdateStr(fromdateStr);
		tDemands.setFromdate(DateUtils.parseDate(fromdateStr));
		tDemands.setReactstatus(TDemands.REACTSTATUS_WAIT);
		//根据传入的cartypeid获取对应的车型
		TCargotype tCargotype = tCargotypeService.get(request.getParameter("cargotypeid"));
		tDemands.setCartype(tCargotype);
		if(tDemands.getDemandid()==null){
			String userid = request.getParameter("userid");
			User user = userService.get(userid);
			tDemands.setCreateBy(user);
			tDemands.setCreateDate(new Date());
		}
		demandsService.save(tDemands);
		return BackResult.build("200", "正在对您的需求进行报价，请耐心等候，为保证您的顺利用车，获得报价响应后请尽快确认支付");
	}
	public BackResult demandList(TDemands tDemands, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = frontUserService.get(request.getParameter("userid"));
		tDemands.setCreateBy(user);
		Page<TDemands> page = new Page<TDemands>(request, response);
		page.setPageNo(Integer.parseInt(request.getParameter("pageNo")));
		page.setPageSize(Integer.parseInt(request.getParameter("pageSize")));
		page = demandsService.findPage(new Page<TDemands>(request, response), tDemands); 
		if (page.getList()==null||page.getList().size()==0) {
			return BackResult.build("400", "未查询到数据");
		}
		map.put("totalCount", page.getCount());
		map.put("demandList", page.getList());
		return BackResult.ok(map);
	}
	public BackResult demandDetail(TDemands tDemands) {
		Map<String, Object> map = new HashMap<String, Object>();
		String demandid = tDemands.getDemandid()+"";
		if (StringUtil.isNotEmpty(demandid)){
			tDemands = demandsService.get(""+tDemands.getDemandid());
			String address = demandsService.getSendAddress(demandid);
			if (StringUtils.isEmpty(address)) {
				address = "";
			}
			tDemands.setSendAddress(address);
			List<DemandsReact> demandsReactList = demandsService.findDemandsReactList(tDemands);
			if (demandsReactList!=null&&demandsReactList.size()>0) {
				for (DemandsReact dr : demandsReactList) {
					dr.setImages((tDemands.getCartype().getImages()));//设置图片
				}
				map.put("reactList",demandsReactList);
			}
			map.put("tDemands", tDemands);
			return BackResult.ok(map);
		}
		return BackResult.build("400", "参数错误");
	}
	public BackResult submitDemandOrder(CuponsInfo cuponsInfo,TOrders orders,TDemands tDemands,Integer reactid, Model model,
			HttpServletRequest request, String userid) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = frontUserService.get(userid);
		orders.setOrderuserid(user.getId());
		
		List<String> messages = Lists.newArrayList(); // 消息
		DemandsReact react = demandsService.getDemandsReact(reactid);
		TDemands demand = new TDemands();
		if(messages.isEmpty()) {
			demand = demandsService.get(react.getDemandid()+"");
			if(!TDemands.REACTSTATUS_SURE.equals(demand.getReactstatus())) {
				messages.add("该定制需求不可支付");
			}
		}
		if (StringUtil.isNotBlank(demand.getOrderid())) {//已经生成了订单
			//删除原来的订单
			tOrdersService.delOrderById(demand.getOrderid());
		}
		if(messages.isEmpty()) {
			if(cuponsInfo.getCuponsId()!=null&&cuponsInfo.getCuponsId().length()>0){
				CuponsInfo b = tCuponsService.getCuponsByRecordId(cuponsInfo.getCuponsId());
				react.setPrice(react.getPrice()-Double.parseDouble(b.getPrice()));
			}
			orders.setDueamount(""+react.getPrice());
			orders.setRealscheid(reactid+"");
			orders.setPurchasenum(tDemands.getVehiclenum()+"");
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				if(pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					orders.setOrderid(orderid+"");
					map.put("orders", orders);
					//修改demand表里的orderid
					demandsService.updateOrderId(orderid+"",demand.getDemandid());
					//改变优惠券使用状态
					if(cuponsInfo.getCuponsId()!=null&&cuponsInfo.getCuponsId().length()>0){
						CuponsInfo a = tCuponsService.getCuponsByRecordId(cuponsInfo.getCuponsId());
						if(Double.parseDouble(orders.getDueamount())+Double.parseDouble(cuponsInfo.getMoney())<Double.parseDouble(a.getMinPrice())){
							return BackResult.build("400", "提交失败");
				    	}
						orderService.updateOrderUseCupon(orders.getOrderid());
						cuponsInfo.setOrderId(orders.getOrderid());
						cuponsInfo.setUseTime(new Date());
						tCuponsService.useCupon(cuponsInfo);
					}
					return BackResult.ok(map);
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		return BackResult.build("400", messages.get(0));
	}
	public BackResult cancel(TDemands tDemands) {
		demandsService.cancel(tDemands);
		return BackResult.build("200", "取消用车需求成功");
	}
	public BackResult deleteDemand(TDemands tDemands) {
		demandsService.deleteDemand(tDemands.getDemandid());
		return BackResult.ok();
	}
}























